package user

import (
	"context"
	"errors"
	"github.com/gogf/gf/v2/net/ghttp"
	v1 "my_user/api/user/v1"
	"my_user/internal/consts"
	"my_user/internal/model"
	"my_user/internal/service"
)

type sUser struct{}

func init() {
	service.RegisterUser(NewUser())
}

func NewUser() *sUser {
	return new(sUser)
}

func (l *sUser) SignIn(ctx context.Context, req *v1.SignInReq) (res *v1.SignInRes, err error) {
	user, err := service.Store().GetUser(req.UserName)
	if user.UserName == "" {
		err = errors.New("username not exist")
		return
	}
	if user.Password != req.Password {
		err = errors.New("password error")
		return
	}
	service.Session().Set(consts.UserNameKey, user.UserName)
	return
}

func (l *sUser) SignOut(ctx context.Context, req *v1.SignOutReq) (res *v1.SignOutRes, err error) {
	//name := service.Session().Get(consts.UserNameKey)
	//fmt.Println(name)
	service.Session().Remove(consts.UserNameKey)
	return
}

func (l *sUser) SignUp(ctx context.Context, req *v1.SignUpReq) (res *v1.SignUpRes, err error) {
	one, _ := service.Store().GetUser(req.UserName)
	if one.UserName == req.UserName {
		err = errors.New("username exist")
		return
	}
	user := model.User{
		UserName: req.UserName,
		Password: req.Password,
		NickName: req.NickName,
	}
	err = service.Store().SetUser(user)
	return
}

func (l *sUser) GetUser(ctx context.Context, req *v1.GetProfileReq) (res *v1.ProfileRes, err error) {
	name := ghttp.RequestFromCtx(ctx).GetCtxVar(consts.UserNameKey)
	user, err := service.Store().GetUser(name.String())
	res = &v1.ProfileRes{
		NickName: user.NickName,
		UserName: user.UserName,
	}
	return
}
